package yolorpc.loadbalancer;


import yolorpc.model.ServiceMetaInfo;

import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * @author yolo
 * @Program RPC
 * @description 随机算法实现负载均衡
 * @create 2025-05-22 17:57
 **/
public class RandomLoadBalancer implements LoadBalancer{
    private final Random random = new Random();

    @Override
    public ServiceMetaInfo select(Map<String, Object> requestParams, List<ServiceMetaInfo> serviceMetaInfoList) {
        if (serviceMetaInfoList.isEmpty()){
            return null;
        }
        int size = serviceMetaInfoList.size();
        // 只有一个服务器的情况，直接返回
        if (size == 1){
            return serviceMetaInfoList.get(0);
        }
        // 随机获取服务器
        return serviceMetaInfoList.get(random.nextInt(size));
    }
}
